package com.ccloud.common.core.tree;

import com.google.common.collect.Lists;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.List;

/**
 * zTree 数据实体类
 */

@Data
@Accessors(chain = true)
public class ZTreeDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * ID
     */
    private Long id;
    /**
     * 父ID
     */
    private Long parentId;
    /**
     * 名称
     */
    private String label;
    /**
     * 是否是父节点
     */
    private boolean parent;
    /**
     * 是否选中
     */
    private boolean checked;
    /**
     * 是否打开
     */
    private boolean open;
    /**
     * 编码
     */
    private String code;

    /**
     * 子节点
     */
    List<ZTreeDTO> children;


    /**
     * @return java.util.List<com.hd.common.common.dto.ZTreeDTO>
     * @author chentailai
     * @description 构造ztree树
     * @date 2020/12/29 4:58 下午
     * @params [list]
     */
    public static List<ZTreeDTO> buildTree(List<ZTreeDTO> list) {
        List<ZTreeDTO> tree = Lists.newArrayList();
        for (ZTreeDTO z : list) {
            if (z.getParentId() == 0) {
                //递归列表
                recursionFn(list, z);
                tree.add(z);
            }
        }
        return tree;
    }

    /**
     * @return void
     * @author chentailai
     * @description 递归列表
     * @date 2020/12/29 5:00 下午
     * @params [list, z]
     */
    private static void recursionFn(List<ZTreeDTO> list, ZTreeDTO z) {
        // 得到子节点列表
        List<ZTreeDTO> childList = getChildList(list, z);
        z.setChildren(childList);
        for (ZTreeDTO child : childList) {
            if (hasChild(list, child)) {
                child.setParent(true);
                //判断是否有子节点
                for (ZTreeDTO n : childList) {
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * @return java.util.List<com.hd.common.common.dto.ZTreeDTO>
     * @author chentailai
     * @description 子节点列表
     * @date 2020/12/29 5:14 下午
     * @params [list, z]
     */
    private static List<ZTreeDTO> getChildList(List<ZTreeDTO> list, ZTreeDTO z) {
        List<ZTreeDTO> tlist = Lists.newArrayList();
        for (ZTreeDTO one : list) {
            if (one.getParentId().equals(z.getId())) {
                tlist.add(one);
            }
        }
        return tlist;
    }

    /**
     * @return boolean
     * @author chentailai
     * @description 是否有子
     * @date 2020/12/29 5:14 下午
     * @params [list, z]
     */
    private static boolean hasChild(List<ZTreeDTO> list, ZTreeDTO z) {
        return getChildList(list, z).size() > 0;
    }
}
